/*import { checkHttpStatus, parseJSON } from '../utils';
import { USER_LOGIN_SUCCESS, USER_LOGIN_FAILURE } from '../contants/index';*/

/*export function userLoginSuccess() {
	return {
		type: USER_LOGIN_SUCCESS,
	}
}  
export function userLogin() {
	return dispatch => {
		dispatch(userLoginSuccess())
	}
	
}*/

import { checkHttpStatus, parseJSON } from '../utils';
import {  USER_LOGIN_SUCCESS, USER_LOGIN_FAILURE,LOGIN_USER_REQUEST} from '../contants/index';
import { browserHistory } from 'react-router'

export function loginUserSuccess(session) {
  localStorage.clear();
  if(session) {
  	localStorage.setItem('session', session);
  }
   localStorage.setItem('isAuthenticated',true);
  return {
    type: LOGIN_USER_SUCCESS,
    payload: {
      session: session
    }
  }
}

export function loginUserFailure(error) {
  localStorage.removeItem('session');
  return {
    type: LOGIN_USER_FAILURE,
    payload: {
      errContent: error.content?error.content:error,
      errCode: error.code
    }
  }
}

export function loginUserRequest() {
  return {
    type: LOGIN_USER_REQUEST
  }
}

 export function loginUser(userPhone,userPass) {
     return function(dispatch) {
         dispatch(loginUserRequest());
         return fetch("http://fengke.net:8081/web/login", {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/json'
         },
             body: JSON.stringify({
                 userPhone: userPhone,
                 userPass: userPass
         })
 })
    .then(checkHttpStatus)
    .then(parseJSON)
   .then(
         response => {
                 if(response.status=="1"){
	                 dispatch(loginUserSuccess(response.data.auth));
	                 
                 }else{
                 	dispatch(loginUserFailure(response.errmsg));
                 }
     },
         error =>{
                 console.log('login fails:'+error);
     })

   }
 }

export function loginSupervisor(userPhone,userPass,role) {
     return function(dispatch) {
         dispatch(loginUserRequest());
         return fetch("http://fengke.net:8081/web/Admin_login", {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/json'
         },
             body: JSON.stringify({
                 userPhone: userPhone,
                 userPass: userPass
         })
 })
    .then(checkHttpStatus)
    .then(parseJSON)
   .then(
         response => {
                 if(response.status=="1"){
	                 dispatch(loginUserSuccess(response.data.auth));
	                 browserHistory.push('/supervisor')
                 }else{
                 	dispatch(loginUserFailure(response.errmsg));
                 }
     },
         error =>{
                 console.log('login fails:'+error);
     })
   }
 }

